/** @jsxImportSource @emotion/react */
import {jsx, css} from "@emotion/react";
import * as React from "react";
import { Tabs, Tab, TabPanel, TabIcon } from "../Tabs";
import theme from "../Theme";
import { Text } from "../Text";
import { Container } from "../Container";
import { storiesOf } from "@storybook/react";
import { Layer } from "../Layer";
import { Button } from "../Button";
import {DarkMode, useTheme, LightMode, DarkRefMode} from "../Theme/Providers";
import {
  IconActivity,
  IconAlertCircle,
  IconAlignLeft,
  IconArrowRight,
  IconArrowLeft,
  IconSettings,
  IconUser,
  IconPackage,
  IconMapPin,
  IconArrowUp
} from "../Icons";
import { Pager} from "../Pager";
import { ExampleList } from "./List.stories";
import {IconButton, IconRefButton} from "../IconButton";
import { MenuList, MenuItem, MenuDivider } from "../Menu";
// @ts-ignore
import { faker } from '@faker-js/faker/locale/zh_CN';
import {CommitInput, Input, InputGroup, InputLine} from "../Form";
import {Vector2} from "@use-gesture/core/dist/declarations/src/types/utils";


const pages = [
    'https://images.pexels.com/photos/62689/pexels-photo-62689.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260',
    'https://images.pexels.com/photos/733853/pexels-photo-733853.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260',
    'https://images.pexels.com/photos/4016596/pexels-photo-4016596.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260',
    'https://images.pexels.com/photos/351265/pexels-photo-351265.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260',
]
function getUser() {
    faker.seed(0);
    return {
        name: faker.name.firstName() + " " + faker.name.lastName(),
        description: faker.lorem.sentence()
    };
}

export const TabsExamples = storiesOf("Tabs_Page", module)
    .add("轮播台searchCancel", () => <Example />)
    .add("嵌套Pager+Pager", () => {
        return <ParentSwipe />;
    })
    .add("Icons", () => {
        return <IconExample />;
    });

const Example = () => {
    const [items, setItems] = React.useState(
        Array.from(new Array(37)).map(() => getUser())
    );
  const [value, setValue] = React.useState(0);
  const theme = useTheme();
    const [filter, setFilter] = React.useState<any>( {} );

    const [form, setForm] = React.useState({ username: "", password: "",
        mobile:''} as any);
    async function doLogin(e: React.FormEvent  | Event)
    {
        console.log("点了form",form);
    }
  return (
    <div
      css={{
        maxWidth: "100vw",
        height: "100vh",
        background: theme.colors.background.tint1
      }}
    >
      <Tabs value={value} onChange={i => setValue(i)}>
        <Tab id="2">首页courseCourse events</Tab>
          <Tab id="settings">第二Settings</Tab>
          <Tab id="4">templatesgenduode1页面</Tab>
          <Tab id="courses">四Courses</Tab>
          <Tab id="5">Team members最后</Tab>
       </Tabs>
       <Pager   lazyLoad={false}  noBind={false}
             value={value}   onRequestChange={i => setValue(i)}
            css={{
                height: '100%',
            }}
        >
            <TabPanel id="company"
                      css={{
                          height: '100%',
                      }}
            >
                <TabContent i={0}/>
            </TabPanel>
            <TabPanel id="person"
                      css={{
                          height: '100%',
                      }}
            >
                <TabContent i={1}/>
            </TabPanel>
            <TabPanel id="person2"
                      css={{
                          height: '100%',
                      }}
            >
                <TabContent i={2}/>
            </TabPanel>
            <TabPanel id="company2"
                      css={{
                          height: '100%',
                      }}
            >
                <TabContent i={3}/>
            </TabPanel>
           <TabPanel id="company4"
                     css={{
                         height: '100%',
                     }}
           >
               <InputLine label={`地址:`}>
                   <CommitInput type="search" placeholder="搜索,可模糊"
                                value={filter.address || ''}  onSave={txt => setFilter( { ...filter, address: txt }) }
                   />
               </InputLine>
               <form  method="post"
                      onSubmit={e =>{ doLogin(e) } }>
                   <div   css={{  marginTop: theme.spaces.md   }}>
                       <InputGroup  label={"账户"}>
                           <Input  required  type="search"
                                   onChange={e => {
                                       setForm({ ...form, username: e.currentTarget.value });
                                   }}
                                   value={form.username}
                                   inputSize="md"
                                   placeholder="账户"
                           />
                       </InputGroup>
                       <div css={{ display: "flex", justifyContent: "flex-end" }}>
                           <Button
                               block
                               component="button"
                               css={{
                                   textAlign: "center",
                                   width: "100%",
                                   marginTop: theme.spaces.md
                               }}
                               type="submit"
                               size="md"
                               intent="primary"
                           >
                             登录1submit
                           </Button>
                           <Button
                               block
                               component="button"
                               css={{
                                   textAlign: "center",
                                   width: "100%",
                                   marginTop: theme.spaces.md
                               }}
                               size="md"
                               intent="primary"
                               onPress={e =>{ console.log("点onPress",form);
                                   doLogin(e) } }
                           >
                               登录2onPress
                           </Button>
                       </div>
                   </div>
               </form>
           </TabPanel>
        </Pager>
    </div>
  );
};


//内部的pager
function SonPagerInner({
  onRequestParentChange,
  onRequestChange,
  value,
  onCannotDragOver
}: any) {
  return (
    <Layer
      elevation="sm"
      css={{
        background: "white",

        width: "100%",
        display: "block",
        borderRadius: 0,
        boxSizing: "border-box",
        overflow: "hidden"
      }}
    >
      <div
        css={{
          boxSizing: "border-box",
          width: "100%",
          overflow: "hidden",
            height: '90vh',
        }}
      >
        <DarkMode>
          <div
            css={{
              position: "relative",
              zIndex: theme.zIndices.sticky,
              background: theme.colors.palette.blue.base
            }}
          >
            <Container
              css={{
                justifyContent: "space-between",
                display: "flex",
                alignItems: "center"
              }}
            >
              <IconButton
                variant="ghost"
                icon={<IconArrowLeft />}
                onPress={() => onRequestParentChange(0)}
                label="Go back父辈Pager的"
              />
              <Text
                variant="h5"
                gutter={false}
                css={{
                  textAlign: "center",
                  padding: theme.spaces.md
                }}
              >
                Messenger
              </Text>
              <LightMode>
                    <MenuList>
                      <MenuItem contentBefore={<IconArrowUp />}>
                        Anything you ask
                      </MenuItem>
                    </MenuList>
              </LightMode>
            </Container>
            <Tabs value={value} onChange={onRequestChange}>
              <Tab id="hello">第一Contacts</Tab>
              <Tab id="cool">Inbox</Tab>
              <Tab id="tables">Notifications</Tab>
              <Tab id="family">最后Family</Tab>
            </Tabs>
          </div>
        </DarkMode>
        <Pager   lazyLoad={false}
               value={value}   onRequestChange={i => onRequestChange(i)}
                onNestDragEnd={onCannotDragOver}
                css={{
                    height: '100%',
                }}
        >
          <TabPanel id="hello" css={{ flex: 1 }}>
            <ExampleList />
          </TabPanel>
          <TabPanel id="cool" css={{ flex: 1, padding: "24px" }}>
            Inbox content2 切换
          </TabPanel>
          <TabPanel id="tables" css={{ flex: 1, padding: "24px" }}>
            Notification list3
          </TabPanel>
          <TabPanel id="players" css={{ flex: 1, padding: "24px" }}>
            Settings tab content 4
          </TabPanel>
        </Pager>
      </div>
    </Layer>
  );
}

function ParentSwipe() {
  const [parentIndex, setParentIndex] = React.useState(0);
  const [childIndex, setChildIndex] = React.useState(0);
    //返回true=脱离控制，交给下一层次的的Pager控制
    const onFatherCannotDrag = React.useCallback(([x, y]:Vector2) => {
        console.log("onFatherCannotDrag跑来  parentIndex=",parentIndex,"x",x);
        return false;
    }, [parentIndex]);

    //依据当前childIndex以及拉动方向，判定是否交给父辈的Pager做切换。
    const onCannotDragOver = React.useCallback(([x, y]:Vector2) => {
        console.log("onCannotDragOver来  childIndex=",childIndex,"x",x);
        if (x < 0 ) {
            if (childIndex >= 3) {
                setParentIndex(0);
            }
        }
        if (x > 0 ) {
            if (childIndex <= 0) {
                setParentIndex(0);
            }
        }
        return true;
    }, [childIndex, setParentIndex]);

    /* paneStyle={css`overflow:auto; background-color: red; `}*/
  return (
    <div
      css={{
        display: "flex",
        justifyContent: "center",
        background: theme.colors.background.tint2
      }}
    >
      <div
        css={{
            width: '100vw',
            height: '100vh',
          borderRadius: 0,
          maxWidth: "100vw",
          overflow: "hidden",
          [theme.mediaQueries.md]: {
            maxWidth: "450px",
            borderRadius: theme.radii.lg
          }
        }}
      >
        <Pager  lazyLoad={false}
                value={parentIndex}   onRequestChange={i => setParentIndex(i)}
                onNestDragEnd={onFatherCannotDrag}
                css={{
                    height: '100%',
                }}
        >
            <TabPanel id="meisp"
                      css={{
                          height: '100%',
                      }}
            >
                <div
                    css={{
                        background: theme.colors.palette.green.base,
                        flex: 1,
                        display: "flex",
                        justifyContent: "center",
                        alignItems: "center"
                    }}
                >
                    <DarkMode>
                        <Text
                            css={{
                                display: "flex",
                                height: "300px",
                                alignItems: "center"
                            }}
                        >
                            <Button
                                variant="ghost"
                                onPress={() => setParentIndex(1)}
                                iconAfter={<IconArrowRight />}
                            >
                                父辈Pager 第一页View next进去 Son:
                            </Button>
                        </Text>
                    </DarkMode>
                </div>

            </TabPanel>

            <TabPanel id="subreport"
                      css={{
                          height: '100%',
                      }}
            >
                <SonPagerInner
                    value={childIndex}
                    onRequestParentChange={(i: number) => setParentIndex(i)}
                    onRequestChange={(i: number) => setChildIndex(i)}
                    onCannotDragOver={onCannotDragOver}
                />
            </TabPanel>
        </Pager>
      </div>
    </div>
  );
}

function TabContent({i}: any) {

    return (   <div style={{
                touchAction: 'none',
                backgroundSize: 'cover',
                backgroundRepeat: `no-repeat`,
                backgroundPosition: `center center`,
                width: "100%",
                height: "100%",
                boxShadow: `0 62.5px 125px -25px rgba(50, 50, 73, 0.5), 0 37.5px 75px -37.5px rgba(0, 0, 0, 0.6)`,
                display: "flex",
                flexDirection: "column",
                alignSelf: "stretch",
                justifyContent: "flex-start",
                flexShrink: 0,
                overflow: "auto",
                outline: "none",
                backgroundImage: `url(${pages[i]})` ,
            }}>
            </div>);
}


function IconExample() {
    const [value, setValue] = React.useState(0);
    const theme = useTheme();
    return (
        <div
            css={{
                display: "flex",
                justifyContent: "center",
                background: theme.colors.background.tint2,
                padding: "0.5rem"
            }}
        >
            <Layer
                elevation="sm"
                css={{
                    maxWidth: "400px",
                    maxHeight: "500px",
                    width: "100%",
                    display: "block",
                    boxSizing: "border-box",
                    overflow: "hidden"
                }}
            >
                <div
                    css={{
                        background: theme.colors.background.tint1,
                        boxSizing: "border-box",
                        width: "100%",
                        overflow: "hidden",
                        display: "flex",
                        flexDirection: "column",
                        height: "200px"
                    }}
                >
                    <div
                        css={{
                            flex: 1
                        }}
                    />
                    <div>
                        <Tabs
                            variant="evenly-spaced"
                            slider={false}
                            css={{ background: theme.colors.background.default }}
                            value={value}
                            onChange={i => setValue(i)}
                        >
                            <Tab id="hello">
                                <TabIcon icon={<IconActivity />} label="Chat" />
                            </Tab>
                            <Tab id="cool">
                                <TabIcon icon={<IconAlertCircle />} label="Annotation" />
                            </Tab>
                            <Tab id="tables">
                                <TabIcon icon={<IconAlignLeft />} label="Application" />
                            </Tab>
                            <Tab id="players">
                                <TabIcon icon={<IconActivity />} label="Build" />
                            </Tab>
                            <Tab id="dsf">
                                <TabIcon icon={<IconActivity />} label="Chart" />
                            </Tab>
                        </Tabs>
                    </div>
                </div>
            </Layer>
        </div>
    );
}

